﻿using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using Bravura.Core.MusicLib;

namespace BravuraWin
{
	public partial class MusicForm : Form, IMusicEngineHost
	{
		private IMusicEngine eng = null;
		private bool _rendering = false;

		public MusicForm()
		{
			InitializeComponent();
		}

		private void buttonAction_Click(object sender, EventArgs e)
		{
			if (_rendering) // cancel
			{
				// cancel
				_rendering = false;
				progressRender.Value = 0;
				labelStatus.Text = "Rendering canceled";
			}
			else // render
			{
				// initialize
				eng = new MusicEngine(this, int.Parse(comboBoxRate.Text));
				eng.Load(new FileInfo(textBoxProjectFile.Text));

				groupBoxParams.Enabled = false;
				labelStatus.Text = "Rendering";
				buttonAction.Text = "Cancel";
				_rendering = true;

				try
				{
					// render
					if (numEnd.Value > numStart.Value)
					{
						eng.Render((int)numStart.Value, (int)numEnd.Value);
					}
					else
					{
						eng.Render();
					}
				}
				catch (Exception ex)
				{
					#if DEBUG
					MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
					#else
					MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
					#endif
					labelStatus.Text = "Error occurred";
					_rendering = false;
				}

				if (_rendering)
				{
					labelStatus.Text = "Rendering complete";
				}

				groupBoxParams.Enabled = true;
				buttonAction.Text = "Render";
				_rendering = false;
			}
		}

		private void textBoxProjectFile_TextChanged(object sender, EventArgs e)
		{
			buttonAction.Enabled = File.Exists(textBoxProjectFile.Text);
		}

		private void buttonChooseFile_Click(object sender, EventArgs e)
		{
			OpenFileDialog dlg = new OpenFileDialog();
			dlg.Filter = "XAML files (*.xaml)|*.xaml";
			DialogResult dr = dlg.ShowDialog();
			if (dr == DialogResult.OK)
			{
				textBoxProjectFile.Text = dlg.FileName;
			}
		}

		#region IMusicEngineHost

		bool IMusicEngineHost.ShouldContinue()
		{
			return _rendering;
		}

		void IMusicEngineHost.LogProgress(int progress, int total)
		{
			progressRender.Value = progress + 1;
			progressRender.Maximum = total;
			Application.DoEvents();
		}

		void IMusicEngineHost.LogMessage(IMusicEngine source, TraceLevel severity, string message)
		{
			if (severity == TraceLevel.Error)
			{
				MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		#endregion
	}
}
